/*
 * LoginServlet.java
 *
 * Created on March 29, 2007, 8:15 PM
 */

package controllers;

import java.io.*;
import java.net.*;
import java.sql.SQLException;

import javax.servlet.*;
import javax.servlet.http.*;
import listeners.UserIdWrapper;
import model.Action;
import model.Salesman;

/**
 *
 * @author Alirio
 * @version
 */
public class LoginServlet extends HttpServlet {
  
  private void populateActions(Salesman s) {
    java.sql.Connection cnn = (java.sql.Connection) getServletContext().getAttribute("cnn");
    java.sql.Statement stmt;
    try {
      stmt = cnn.createStatement();
      java.sql.ResultSet rs = stmt.executeQuery("select salesmen_actions.*,actions.name from salesmen_actions,actions where salesmen_actions.action_id=actions.action_id and salesman_id='" + s.getId() + "'");
      
      while (rs.next()) {
        Action a = new Action();
        a.setId(rs.getInt("action_id"));
        a.setName(rs.getString("name"));
        s.addAction(a);
      }
      rs.close();
      stmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  
  /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String forward = "";
    String action = request.getParameter("action");
    String empresa = request.getParameter("empresa");
    
    if (action.equals("check")) {
      String msg = "";
      String username = request.getParameter("sm");
      String password = request.getParameter("cm");
      java.sql.Connection cnn = (java.sql.Connection) getServletContext().getAttribute("cnn");
      java.sql.Statement stmt;
      java.sql.Statement stmt1;
      String motivo="";
      synchronized (this) {
        try {
          boolean is = false;
          stmt1 = cnn.createStatement();
          java.sql.ResultSet rs1 = stmt1.executeQuery("select * from system");
          rs1.next();
          motivo=rs1.getString("motivo");
          if (rs1.getString("estado").equals("A"))
          {  
          stmt = cnn.createStatement();
          java.sql.ResultSet rs = stmt.executeQuery("select * from salesmen where salesman_id='"+username+"'");
          
          while (rs.next()) {
            is = true;
            if (rs.getString("comments").equals(password)) {
              //if (rs.getByte("logged") == 0) {
              if (true) {
                HttpSession session = request.getSession();
                String sessionId = session.getId();
                Salesman salesman = new Salesman();
                salesman.setId(username);
                salesman.setName(rs.getString("name"));
                salesman.setTopSerial(rs.getInt("top_serial"));
                salesman.setBottomSerial(rs.getInt("bottom_serial"));
                populateActions(salesman);
                session.setAttribute("salesman", salesman);
                session.setAttribute("empresa", empresa);
               
                session.setAttribute("useridwrapper", new UserIdWrapper(username));
                //actualizamos el status de logged
                java.sql.Statement stmt2 = cnn.createStatement();
                stmt2.executeUpdate("update salesmen set logged=1, session_id='" + sessionId+ "' where salesman_id='"+username+"'");
                stmt2.close();
                
                //colocamos una cookie para posteriores intentos de login
                Cookie cookie = new Cookie("webpedidos", username);
                Cookie cookie2 = new Cookie("webpedidosid", sessionId);
                cookie.setMaxAge(180);
                cookie2.setMaxAge(180);
                response.addCookie(cookie);
                response.addCookie(cookie2);
                
                forward = "OrderServlet?action=showCustomers";
              } else {
                String sid = rs.getString("session_id");
                Cookie[] cookies = request.getCookies();
                boolean pase = false;
                boolean pase2 = false;
                for (int i = 0; i < cookies.length; i++) {
                  if (cookies[i].getName().equals("webpedidos") && cookies[i].getValue().equals(username)) {
                    pase = true;
                    continue;
                  }
                  if (cookies[i].getName().equals("webpedidosid") && cookies[i].getValue().equals(sid)) {
                    pase2 = true;
                    continue;
                  }
                  
                }
                if (pase && pase2) {
                  HttpSession session = request.getSession();
                  Salesman salesman = new Salesman();
                  salesman.setId(username);
                  salesman.setName(rs.getString("name"));
                  salesman.setTopSerial(rs.getInt("top_serial"));
                  salesman.setBottomSerial(rs.getInt("bottom_serial"));
                  populateActions(salesman);
                  session.setAttribute("salesman", salesman);
                  
                  session.setAttribute("useridwrapper", new UserIdWrapper(username));
                  
                  //colocamos una cookie para posteriores intentos de login
                  Cookie cookie = new Cookie("webpedidos", username);
                  cookie.setMaxAge(180);
                  response.addCookie(cookie);
                  forward = "OrderServlet?action=showCustomers";
                } else {
                  is = false;
                  msg = "Usuario ya inicio sesion en otro movil";
                }
              }
            } else {
              is = false;
              msg = "Error en login. Verifique sus datos de inicio de sesion";
            }
          }
          rs.close();
          stmt.close();
          
          }
          else
          {
            is=false;
            msg = "El Sistema esta temporalmente desactivado por : "+ motivo;
          }
          
          if (!is) {
            forward = "error.jsp?msg=" + msg;
          }
        } catch (SQLException ex) {
          ex.printStackTrace();
          forward = "error.jsp?msg=Error creando objetos SQL:" + ex.getMessage();
        }
      }
    }
    
    if (action.equals("logoff")) {
      HttpSession session = request.getSession();
      Salesman salesman = (Salesman) session.getAttribute("salesman");
      
      session.invalidate(); //aqui la clase listeners.UserIdWrapper actualiza el status de logged
      forward = "login.jsp";
    }
    
    if (action.equals("Cambiar")) {
      java.sql.Connection cnn = (java.sql.Connection) getServletContext().getAttribute("cnn");
      java.sql.Statement stmt;
      HttpSession session = request.getSession();
      String username = ((Salesman) session.getAttribute("salesman")).getId();
      String newPass = request.getParameter("newComment");
      String repPass = request.getParameter("repComment");
      if (!newPass.equals("") && newPass.equals(repPass)) {
        try {
          stmt = cnn.createStatement();
          long ar = stmt.executeUpdate("update salesmen set comments='"+newPass+"' where salesman_id='"+username+"'");
          
          if (ar == 0) {
            forward = "error.jsp?msg=Error cambiando la clave";
          } else {
            forward = "OrderServlet?action=showHome";
          }
          
          stmt.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
          forward = "error.jsp?msg=Error creando objetos SQL";
        }
      } else {
        request.setAttribute("err", "Claves no coinciden<br/>");
        forward = "usrChgpwd.jsp";
      }
    }
    
    if (action.equals("Cancelar Cambio")) {
      forward = "OrderServlet?action=showHome";
    }
    
    RequestDispatcher rd = request.getRequestDispatcher(forward);
    rd.forward(request, response);
    
    
  }
  
  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /** Handles the HTTP <code>GET</code> method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    processRequest(request, response);
  }
  
  /** Handles the HTTP <code>POST</code> method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    processRequest(request, response);
  }
  
  /** Returns a short description of the servlet.
   */
  public String getServletInfo() {
    return "Short description";
  }
  // </editor-fold>
}
